<template>
  <div class="app-container customer-div" style="overflow-x: auto">
    <!-- tabs标签页  -->
    <el-tabs v-model="listQuery.groupBy" type="card" @tab-click="handleClick1">
      <el-tab-pane label="未成交统计" name="all"></el-tab-pane>
      <el-tab-pane label="按品类" name="goodsName"></el-tab-pane>
      <el-tab-pane label="按牌号" name="goodsSn"></el-tab-pane>
      <el-tab-pane label="按采购员" name="chargeUser"></el-tab-pane>
      <el-tab-pane label="按业务员" name="inquiryUser"></el-tab-pane>
      <el-tab-pane label="按客户" name="customerName"></el-tab-pane>
      <el-tab-pane label="我的" name="my"></el-tab-pane>
    </el-tabs>
    <!-- 搜索栏  -->
    <el-form :inline="true" :model="listQuery" size="mini" label-width="50px">
      <el-form-item label="日期：">
        <el-date-picker
          v-model="listQuery.inquiryDate"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" label-width="0px">
        <el-radio-group v-model="listQuery.groupDate">
          <el-radio-button label="day">按日</el-radio-button>
          <el-radio-button label="month">按月</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="品名:"
        label-width="50px"
        v-if="listQuery.groupBy == 'goodsName'"
      >
        <el-select
          clearable
          v-model="listQuery.goodsName"
          filterable
          allow-create
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :loading="optionsLoading"
          @focus="getGoodsSortList"
        >
          <el-option
            v-for="item in options"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryName"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="牌号:"
        label-width="50px"
        v-if="listQuery.groupBy == 'goodsSn'"
      >
        <el-input v-model="listQuery.goodsSn" clearable></el-input>
      </el-form-item>

      <el-form-item
        label="采购员:"
        label-width="70px"
        v-if="listQuery.groupBy == 'chargeUser'"
      >
        <el-select
          v-model="listQuery.chargeUserId"
          placeholder="请选择"
          allow-create
          @focus="getSalesmanList"
          filterable
          clearable
        >
          <el-option
            v-for="item in salesMemberList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
            :loading="salesmanLoading"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="业务员:"
        label-width="70px"
        v-if="listQuery.groupBy == 'inquiryUser'"
      >
        <el-select
          v-model="listQuery.userId"
          placeholder="请选择"
          allow-create
          @focus="getsalesList"
          filterable
          clearable
        >
          <el-option
            v-for="item in salesList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
            :loading="salesLoading"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="客户名称:"
        label-width="80px"
        v-if="listQuery.groupBy == 'customerName'"
      >
        <el-autocomplete
          clearable
          @clear="clearCustom"
          class="inline-input"
          value-key="customerName"
          :fetch-suggestions="querySearch"
          v-model="customerName"
          placeholder="请输入内容"
          @select="handleSelectCustomerName"
          :trigger-on-focus="false"
        ></el-autocomplete>
      </el-form-item>

      <el-form-item>
        <el-button
          style="margin-left: 10px"
          type="primary"
          @click="getUnsettleReport"
        >
          查询
        </el-button>
        <el-button
          :loading="btnLoading"
          style="margin-left: 10px"
          @click="downloadExcel"
          type="primary"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 卡片 -->
    <el-card class="box-card">
      <div>
        <p class="inquiryNumber">{{ cardTotal.inquiryCountTotal }}</p>
        <span class="inquiryStr">询价次数</span>
      </div>
      <div>
        <p class="inquiryNumber">{{ cardTotal.priceCountTotal }}</p>
        <span class="inquiryStr">报价次数</span>
      </div>
      <div>
        <p class="inquiryNumber">{{ cardTotal.inquiryCancelTotal }}</p>
        <span class="inquiryStr">未成交次数</span>
      </div>
    </el-card>
    <!-- echarts图标 -->
    <div
      id="unSettleChart"
      style="height: 400px; margin-top: 20px"
      v-loading="loadingChart"
    ></div>
    <!-- 数据列表 -->
    <el-table
      :data="tableData"
      style="width: 98%; margin-top: 20px"
      border
      height="500"
      :default-sort="{
        prop: ['inquiryCount', 'inquiryCancel'],
        order: 'descending',
      }"
      :header-cell-style="{ background: '#fafafa', height: '48px', padding: 0 }"
    >
      <el-table-column
        v-if="listQuery.groupDate == 'day'"
        prop="inquiryDate"
        label="日期"
        min-width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-if="listQuery.groupDate == 'month'"
        prop="inquiryDate"
        label="月份"
        min-width="130"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-if="listQuery.groupBy == 'goodsName'"
        prop="goodsName"
        label="品名"
        min-width="130"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-if="listQuery.groupBy == 'goodsSn'"
        prop="goodsSn"
        label="牌号"
        min-width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-if="listQuery.groupBy == 'chargeUser'"
        prop="chargeUser"
        label="采购员"
        min-width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-if="listQuery.groupBy == 'inquiryUser'"
        prop="inquiryUser"
        label="业务员"
        min-width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-if="listQuery.groupBy == 'inquiryUser'"
        prop="departmentName"
        label="军团"
        min-width="130"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-if="listQuery.groupBy == 'customerName'"
        prop="customerName"
        label="客户名称"
        min-width="180"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="inquiryCount"
        label="询价总次数"
        sortable
        min-width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="inquiryCancel"
        label="取消询价次数"
        sortable
        min-width="130"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="unPriceCount"
        label="未报价次数"
        min-width="130"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="priceCount"
        label="报价次数"
        min-width="130"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="unOrderCount"
        label="未成交次数"
        min-width="130"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-for="(item,index) in unOrderReasonList"
        :key="index"
        :prop="item.key"
        :label="item.name"
        min-width="130"
        align="center"
      >
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
const defaultListQuery = {
  groupBy: "all", //分组：goodsName（品名） goodsSn（牌号） chargeUser（采购员） inquiryUser（询价人） customerName（客户名）
  groupDate: "day", //时间分组：day 按年月日分组 month 按年月分组
  orderBy: "", //排序：inquiryCountDesc（询价总数降序） inquiryCountAsc（询价总数升序） inquiryCancelDesc（询价取消数降序） inquiryCancelAsc（询价取消数升序） unPriceCountDesc（未报价数降序）unPriceCountAsc（未报价数升序）
  inquiryDate: [], //搜索时间段 2022-10-11
  goodsName: "", //品名
  goodsSn: "", //牌号
  chargeUserId: "", //采购员
  userId: "", //业务员
  customerId: "", //客户名称
};
import { goodsSortList } from "@/api/allInLine/goods.js";
import { salesmanList, getCustomerList } from "@/api/allInLine/inquiry.js";
import {getOrderUsersList} from '@/api/partner'
import { getUnsettleReportAPI } from "@/api/allInLine/report.js";
import { mapGetters } from "vuex";
import { formatDate } from "@/utils/date";
import echarts from "echarts";
export default {
  name: "unsettleReport",
  data() {
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "7天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "30天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      btnLoading: false,
      loadingChart: false,
      // 表格数据
      tableData: [],
      cardTotal: {},
      options: [], //品名
      optionsLoading: false,
      // 采购员列表
      salesMemberList: [],
      salesmanLoading: false,
      // 业务员列表
      salesList: [],
      salesLoading: false,
      // 客户名称列表
      customerName: "",
      xList: [],
      yList: [],
      // 未成交原因列表
      unOrderReasonList:[]
    };
  },
  computed: {
    ...mapGetters(["name", "mobile", "userId"]),
  },
  created() {
    let now = new Date();
    let today = formatDate(now, "yyyy-MM-dd");
    this.listQuery.inquiryDate = [today, today];
    this.getUnsettleReport();
  },
  mounted() {
    this.initChart();
  },
  methods: {
    // 清空
    clearCustom() {
      this.listQuery.customerId = "";
    },
    //选择客户名称
    handleSelectCustomerName(item) {
      this.listQuery.customerId = item.customerId;
    },
    //客户名称输入匹配
    querySearch(queryString, cb) {
      getCustomerList({ keywords: queryString, tab: "all" }).then((res) => {
        cb(res);
      });
    },
    // 获取业务员列表
    async getsalesList() {
      this.salesLoading = true;
      const res = await getOrderUsersList({ departmentType: "" });
      this.salesList = res;
      this.salesLoading = false;
    },
    // 获取采购员列表
    async getSalesmanList() {
      this.salesmanLoading = true;
      const res = await getOrderUsersList({ departmentType: "purchase" });
      this.salesMemberList = res;
      this.salesmanLoading = false;
    },
    // 获取品名列表
    getGoodsSortList() {
      this.optionsLoading = true;
      goodsSortList().then((res) => {
        this.options = res;
        this.optionsLoading = false;
      });
    },
    // 配置图表
    initChart() {
      const chart = echarts.init(document.getElementById("unSettleChart"));
      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          boundaryGap: [0, 0.01],
        },
        yAxis: {
          type: "category",
          name: "未成交原因",
          data: this.yList,
        },
        series: [
          {
            type: "bar",
            data: this.xList,
            itemStyle: {
              color: "#669999",
            },
          },
        ],
      };
      chart.setOption(option);
    },
    //获取未成交分析列表
    async getUnsettleReport() {
      this.loadingChart = true;
      const res = await getUnsettleReportAPI(this.listQuery);
      this.cardTotal = res.total;
      this.tableData = res.list;
      this.unOrderReasonList = res.unOrderReasonKey
      this.xList = res.total.orderFaildListByX;
      this.yList = res.total.orderFaildListByY;
      this.initChart();
      this.loadingChart = false;
    },
    // tab栏切换
    handleClick1() {
      this.listQuery.goodsName = "";
      this.listQuery.goodsSn = "";
      this.listQuery.chargeUserId = "";
      this.listQuery.userId = "";
      this.listQuery.customerId = "";
      this.customerName = "";
      this.getUnsettleReport();
    },
    //下载excle
    downloadExcel() {
      let params = JSON.parse(JSON.stringify(this.listQuery));
      params.isExport = 1;
      this.btnLoading = true;
      getUnsettleReportAPI(params)
        .then((res) => {
          this.btnLoading = false;
          require.ensure([], () => {
            const { export_json_to_excel } = require("sheet/Export2Excel");
            const tHeader = res.title;
            const filterVal = res.columns;
            const list = res.list;
            const data = this.formatJson(filterVal, list);
            export_json_to_excel(tHeader, data, res.fileName);
          });
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },
    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
  },
};
</script>

<style scoped lang="scss">
.el-card {
  width: 500px;
}
.el-card /deep/ .el-card__body {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 90px;
  .inquiryNumber {
    text-align: center;
    font-size: 18px;
    font-weight: 500;
  }
  .inquiryStr {
    font-size: 14px;
    color: #ccc;
  }
}
</style>
